<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>ZLTool-设备管理</title>
    <link rel="icon" href="/static/icon.png">
    <link rel="stylesheet" href="/static/base.css"/>
    <!-- 引入样式 -->
    <link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/element-ui/2.15.7/theme-chalk/index.min.css" />
    <script src="https://cdn.bootcdn.net/ajax/libs/vue/2.6.14/vue.min.js"></script>
    <!-- 引入组件库 -->
    <script src="https://cdn.bootcdn.net/ajax/libs/element-ui/2.15.7/index.min.js"></script>

    <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.21.1/axios.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/qs/6.10.1/qs.min.js"></script>
    <script src="https://cdn.bootcdn.net/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

    <style>
        .pagination {
            margin-top: 16px;
            text-align: right;
        }

        .latlng-border {
            position: relative;
            border-top-right-radius: 0px;
            border-bottom-right-radius: 0px;
        }

        .latlng-border input {
            border-width: 0px;
            vertical-align: center;
            margin: 0px !important;
            padding: 0px !important;
            border-radius: 0px;
            height: 36px;
            width: 100px;
        }

        .latlng-label {
            font-size: 13px;
            margin-right: 20px;
            color: #909399;
        }

        .latlng-btn button {
            background-color:  #F5F7FA;
            color: #909399;
            border-left: 0px;
            border-top-left-radius: 0px;
            border-bottom-left-radius: 0px;
        }

        .latlng-border .el-input {
            width: 110px;
        }

        .clear-latlng {
            cursor: pointer;
            opacity: 0.5;
        }

    </style>
</head>
<body>
<div id="app">
    <layout>
        <template #menu>
            <top-menu index="devices.html"></top-menu>
        </template>
        <template #main>
            <el-main>
                <el-form :inline="true" :model="searchForm">
                    <el-form-item>
                        <el-input v-model="searchForm.name" placeholder="设备名称" clearable></el-input>
                    </el-form-item>
                    <el-form-item>
                        <el-select v-model="searchForm.tags" multiple filterable remote reserve-keyword
                                   :loading="tagLoading" :remote-method="tagRemoteMethod"
                                   style="width: 265px"
                                   value-key="id"
                                   placeholder="请选择标签(关键字查找,*查询所有)">
                            <el-option v-for="item in allTags" :key="item.id" :label="item.content" :value="item.id">
                                {{item.content}}
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item>
                        <el-button @click="loadList">查询</el-button>
                    </el-form-item>
                    <el-form-item>
                        <el-button @click="showAddDialog" type="primary">添加设备</el-button>
                    </el-form-item>
                </el-form>
                <el-table :data="tableData" style="width: 100%" v-loading="tableLoading">
                    <el-table-column label="ID" prop="id" width="180"></el-table-column>
                    <el-table-column prop="name" label="名称" width="200"></el-table-column>
                    <el-table-column prop="linkId" label="业务ID" width="180"></el-table-column>
<!--                    <el-table-column prop="stream" label="流地址" :show-overflow-tooltip="true"></el-table-column>-->
                    <el-table-column label="经纬度" width="180">
                        <template slot-scope="scope">
                            <span v-if="scope.row.longitude">{{ scope.row.longitude }},{{ scope.row.latitude }}</span>
                            <span v-else>--</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="创建时间" width="160">
                        <template slot-scope="scope">
                            {{ unix2Date(scope.row.created_at) }}
                        </template>
                    </el-table-column>
                    <el-table-column prop="remark" label="备注"></el-table-column>
                    <el-table-column label="操作" width="170" header-align="center" align="center">
                        <template slot-scope="scope">
                            <el-button size="mini" type="text" @click="player(scope.row)">预览</el-button>
                            <el-button size="mini" type="text" @click="modify(scope.row)">编辑</el-button>
                            <el-button size="mini" type="text" @click="remove(scope.row)">删除</el-button>
                        </template>
                    </el-table-column>
                </el-table>
                <el-pagination
                        :hide-on-single-page="true"
                        @current-change="handleCurrentChange"
                        :current-page.sync="current"
                        :page-size="pageSize"
                        layout="prev, pager, next"
                        class="pagination"
                        :total="total">
                </el-pagination>
            </el-main>
        </template>

    </layout>

    <el-dialog :title="addForm.id ? '编辑设备' : '添加设备'" :visible.sync="addDialogVisible" width="50%" :close-on-click-modal="false"
               @closed="closeAddDialog">
        <el-form :model="addForm" ref="addForm" :rules="addRules" label-width="100px"
                 v-loading="formLoading">
            <el-form-item label="名称" prop="name">
                <el-input v-model="addForm.name" placeholder="设备名称" clearable></el-input>
            </el-form-item>
            <el-form-item label="业务ID" prop="linkId">
                <el-input v-model="addForm.linkId" placeholder="可以存放和业务关联的数据" clearable></el-input>
            </el-form-item>
            <el-form-item label="流地址(url)" prop="stream">
                <el-input v-model="addForm.stream" autocomplete="off" placeholder="rtsp、rtmp、mp4 等"
                          clearable></el-input>
            </el-form-item>
            <el-form-item label="经纬度" prop="latlng">
                <div  style="display: flex">
                    <div class="el-input__inner latlng-border">
                        <el-input v-model="addForm.longitude" placeholder="经度(-180 - 180)" maxLength="12"></el-input>,&nbsp;
                        <el-input v-model="addForm.latitude" placeholder="纬度(-90 - 90)" maxLength="11"></el-input>
                        <i class="el-input__icon el-icon-circle-close clear-latlng" style="float:right" @click="clearLatlng"></i>
                    </div>
                    <div class="latlng-btn" title="选取点位">
                        <el-button @click="pickLocation" icon="el-icon-map-location">地图选点</el-button>
                    </div>
                </div>
            </el-form-item>
            <el-form-item label="标签">
                <el-select v-model="addForm.tags" multiple filterable remote reserve-keyword allow-create
                           :default-first-option="true" style="width: 100%"
                           :loading="tagLoading" :remote-method="tagRemoteMethod"
                           value-key="id"
                           placeholder="请输入关键字(*全部)选择标签,如找不到标签直接回车关键字以添加">
                    <el-option v-for="item in allTags" :key="item.id" :label="item.content" :value="item">
                        {{item.content}}
                    </el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="备注">
                <el-input type="textarea" v-model="addForm.remark" autocomplete="off"
                          :autosize="{ minRows: 3, maxRows: 6}"
                          maxlength="50" show-word-limit clearable></el-input>
            </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
            <el-button @click="addDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="addEvent" :disabled="formLoading">提 交</el-button>
        </span>
    </el-dialog>

    <el-dialog title="地图选点" width="80%" top="2vh" v-if="mapDialogVisible" :visible.sync="mapDialogVisible" @closed="closeMapDialog">
        <tdt-map @selected="mapSelected" :latlng="selectedLatlng" ref="tdtMap" height="70vh"></tdt-map>
        <span slot="footer" class="dialog-footer">
            <span v-if="selectedLatlng" class="latlng-label">当前经纬度 {{ selectedLatlng}}</span>
            <el-button type="primary" @click="pickLatlng">确定</el-button>
        </span>
    </el-dialog>

    <player-dialog :visible.sync="playerDialogVisible" ref="playerDialog"></player-dialog>

</div>
</body>
<script src="/static/layout.js"></script>
<script src="/static/menu.js"></script>
<script src="/static/request.js"></script>
<script src="/static/tdtmap.js"></script>
<script src="/static/jessibuca/index.js"></script>
<script src="/static/jessibuca/player.js"></script>
<script src="/static/player-dailog.js"></script>
<script src="/static/tdt.js?v=4.0&tk=ec109e92ddb998763066e3943fd0e1a5" type="text/javascript" defer></script>
<script src="/static/tdt_area.js" type="text/javascript" defer></script>

<script>

    var t = new Vue({
        el: '#app',
        data: function() {
            return {
                searchForm: {
                    tags: [],
                    name: ''
                },
                addForm: {
                    id: '',
                    linkId: '',
                    name: '',
                    stream: '',
                    longitude: '',
                    latitude: '',
                    remark: '',
                    tags: []
                },
                allTags: [],
                selectedLatlng: null,
                tableLoading: false,
                playerDialogVisible: false,
                formLoading: false,
                tagLoading: false,
                tableData: [],
                addDialogVisible: false,
                mapDialogVisible: false,
                current: 1,
                pageSize: 0,
                total: 0,
                addRules: {
                    name: [
                        {required: true, message: '请输入名称', trigger: 'blur'},
                    ],
                    stream: [
                        {required: true, message: '请输入原始流地址', trigger: 'blur'},
                    ],
                }
            }
        },
        created: function () {
            this.$nextTick(() => {
                this.loadList()
            });
        },
        methods: {
            showAddDialog() {
                this.addDialogVisible = true
            },

            //添加
            addEvent() {
                this.$refs["addForm"].validate((valid) => {
                    if (valid) {
                        // 添加流
                        this.formLoading = true

                        let n = []

                        if(this.addForm.tags) {
                            this.addForm.tags.forEach(t=>{
                                if(typeof t === 'string') {
                                    //字符串
                                    n.push({"content": t})
                                } else {
                                    n.push(t)
                                }
                            })
                        }

                        nf = JSON.parse(JSON.stringify(this.addForm))
                        nf.tags = n

                        requestJson.post(
                            `/device/${this.addForm.id ? 'update' : 'add'}`,
                            nf
                        ).then(res => {
                            if (res.data) {
                                let data = res.data;
                                if (data.code === 0) {

                                    //当前页最后一条
                                    if(this.tableData.length === this.pageSize) {
                                        //当前是当前页最后一条，则页数需要+1
                                        this.current += 1
                                    }

                                    this.loadList()
                                    this.formLoading = false
                                    this.addDialogVisible = false
                                } else {
                                    this.formLoading = false
                                    this.$message.error(data.msg);
                                }
                            }
                            this.formLoading = false
                        }).catch(onError);

                    } else {
                        return false;
                    }
                });
            },

            loadList() {
                this.tableLoading = true
                var params = new URLSearchParams()
                params.append('currentPage', this.current)
                params.append("name", this.searchForm.name)

                this.searchForm.tags.forEach(t=>{
                    params.append("tags", t)
                })

                // searchForm
                request.post('/device/page', params).then(res => {
                    this.tableLoading = false
                    if (res.data) {
                        let data = res.data;
                        if (data.code === 0) {
                            this.tableData = data.data
                            this.total = data.total
                            this.pageSize = data.pageOffset
                        } else {
                            this.$message.error(data.msg);
                        }
                    }
                }).catch(onError);
            },

            player(r) {
                this.playerDialogVisible = true
                //播放
                this.$nextTick(() => {
                    this.$refs["playerDialog"].showLoad()

                    addStreamForm = {
                        vhost: "__default__",
                        app: "live",
                        stream: r.id,
                        url: r.stream,
                    },

                    request.get(
                        '/zl/api/addStreamProxy?' + Qs.stringify(addStreamForm),
                    ).then(res => {
                        if (res.data) {
                            let data = res.data;
                            if (data.code === 0) {
                                let that = this
                                setTimeout(() => {
                                    that.$refs["playerDialog"].load(r.id)
                                }, 2000);

                            } else {
                                this.$message.error(data.msg);
                            }
                        }
                    }).catch(onError);
                })
            },

            //修改
            modify(r) {
                r.tags = []
                this.addForm = JSON.parse(JSON.stringify(r))
                this.addDialogVisible = true
                let that = this
                that.loadDeviceTags(r.id)
            },

            //获取设备标签
            loadDeviceTags(id) {
                this.formLoading = true
                request.post(`/device/getTags/${id}`).then(res => {
                    this.formLoading = false
                    if (res.data) {
                        let data = res.data;
                        if (data.code === 0) {
                            this.addForm.tags = data.data
                            //初始化时，添加现有的到列表中
                            this.allTags = data.data
                        } else {
                            this.$message.error(data.msg);
                        }
                    }
                }).catch(onError);
            },

            //删除
            remove(row) {
                this.$confirm(`确认删除设备【${row.name}】吗?`, '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    request.post(`/device/delete/${row.id}`).then(res => {
                        if (res.data) {
                            let data = res.data;
                            if (data.code === 0) {

                                //非第一页
                                if(this.current > 1 && this.tableData.length === 1) {
                                    //当前不是第一页，如果删除的是某一页的最后一条，则页数需要减1
                                    this.current -= 1
                                }

                                this.loadList()
                            } else {
                                this.$message.error(data.msg);
                            }
                        }
                    }).catch(onError);
                }).catch(() => { });
            },

            //页数
            handleCurrentChange(val) {
                this.current = val
                this.loadList()
            },

            closeAddDialog() {
                this.$refs["addForm"].resetFields()
                this.addForm = {}
                this.clearLatlng()
                this.selectedLatlng = null
                this.formLoading = false
                this.allTags = []
            },

            //清除经纬度
            clearLatlng() {
                this.addForm.latitude = ''
                this.addForm.longitude = ''
            },

            //选择地图
            pickLocation() {
                this.mapDialogVisible = true
                if(this.addForm.latitude && this.addForm.longitude) {
                    let lnglat = new T.LngLat(this.addForm.longitude, this.addForm.latitude)
                    this.selectedLatlng = lnglat
                }
            },

            closeMapDialog() {
                this.$refs.tdtMap.resetMap()
                this.selectedLatlng = null
            },

            //地图选中后
            mapSelected(lnglat) {
                this.selectedLatlng = lnglat
            },

            //选中地图点位
            pickLatlng() {
                if(this.selectedLatlng) {
                    this.addForm.longitude = this.selectedLatlng.getLng()
                    this.addForm.latitude = this.selectedLatlng.getLat()
                    this.mapDialogVisible = false
                } else {
                    this.$message.warning('您未选择点位，点击对话框外可以直接关闭地图');
                }
            },

            //远程搜索标签
            tagRemoteMethod(query, callback) {
                if (query !== '') {
                    this.tagLoading = true;

                    request.post(`/sys/tags/list`,
                        Qs.stringify({'key': query}, { allowDots: true })
                    ).then(res => {
                        this.tagLoading = false;
                        if (res.data) {
                            let data = res.data;
                            if (data.code === 0) {
                                this.allTags = data.data
                                if(callback) {
                                    callback()
                                }
                            } else {
                                this.allTags = [];
                            }
                        } else {
                            this.allTags = [];
                        }
                    }).catch(onError);

                } else {

                }
            },

            unix2Date(ud) {
                if(ud) {
                    var dataStr = moment(ud).format('YYYY-MM-DD HH:mm:ss')
                    return dataStr
                }
                return "--"
            }
        }
    })

</script>
</html>